var express = require('express');
var router = express.Router();

var UserToken = require('../db/user_tokens.js');
var indexDao = require('../dao/index.js');
var indexRoutes = module.exports;

/**
 * 首页
 * @param  token  (可不传)
 * @param  cid    (可不传)
 * @param  sort_scoreh2l (可不传)
 * @param  sort_scorel2h (可不传)
 * @param  high_volume  (可不传)
 * @param  key_word (可不传)
 *         url/index/show
 */
indexRoutes.show = function(req, res) {
    var par = req.body;
    if(!par.size) par.size = 10;
    par.size = parseInt(par.size);
    if(!par.page) {
        par.start = 0;
    } else {
        par.start = (parseInt(par.page) - 1) * parseInt(par.size);
    }
    if(par.token) {
        UserToken.checkAllLogin(par.token, null, function (err, errCode, userInfo) {
            if (err) {
                return res.json(new ERR(err, 400));
            }
            if(userInfo.isAdmin)  return res.json('账号或密码有误，请重试！', 400);
            par.uid = userInfo.uid;
            indexDao.show(par, function(err, result){
                if(err) {
                    res.json(new ERR(err, 400));
                } else {
                    res.json(new PKG(result));
                }
            });
        });
    } else {
        indexDao.show(par, function(err, result) {
            if(err) {
                res.json(new ERR(err, 400));
            } else {
                res.json(new PKG(result));
            }
        });
    }
}
router.post('/show', indexRoutes.show);

module.exports = router;
